package com.zhang.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.client.ProductFeignClient;
import com.zhang.constant.MqConst;
import com.zhang.entity.OrderDetail;
import com.zhang.entity.OrderInfo;
import com.zhang.enums.ProcessStatus;
import com.zhang.mapper.OrderInfoMapper;
import com.zhang.service.OrderDetailService;
import com.zhang.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.util.HttpClientUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 订单表 订单表 服务实现类
 * </p>
 *
 * @author zbw
 * @since 2022-04-20
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Value("${cancel.order.delay}")
    private Integer cancelOrderDelay;
    //保存订单基本信息和详情信息
    @Override
    public Long saveOrderAndDetail(OrderInfo orderInfo) {
        //商品对外交易号
        String outTradeNo="atguigu"+System.currentTimeMillis();
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setTradeBody("欢迎来到新世界!");
        orderInfo.setCreateTime(new Date());
        //订单过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,15);
        orderInfo.setExpireTime(instance.getTime());
        //订单的进度状态
        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
        //保存订单基本信息
        baseMapper.insert(orderInfo);
        //保存订单详情信息
        Long orderId = orderInfo.getId();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setOrderId(orderId);
        }
        orderDetailService.saveBatch(orderDetailList);
        //发送一个延迟消息，超时自动取消订单
        rabbitTemplate.convertAndSend(MqConst.CANCEL_ORDER_EXCHANGE,
                MqConst.CANCEL_ORDER_ROUTE_KEY,
                orderId,
                correlationData->{
                    correlationData.getMessageProperties().setDelay(cancelOrderDelay);
                    return correlationData;
                });
        return orderId;
    }

    //生成一个流水号给页面作用域
    @Override
    public String generateTradeNo(String userId) {
        String tradeNo = UUID.randomUUID().toString();
        //在redis中也存放一份
        String tradeNoKey="user:"+userId+":tradeNo";
        redisTemplate.opsForValue().set(tradeNoKey,tradeNo);
        return tradeNo;
    }

    //从redis中取出tradeNo并且进行对比
    @Override
    public boolean checkTradeNo(String userId, String tradeNoUI) {
        String tradeNoKey="user:"+userId+":tradeNo";
        String redisTradeNo = (String) redisTemplate.opsForValue().get(tradeNoKey);
        return tradeNoUI.equals(redisTradeNo);
    }

    //提交以后还需要删除redis中的流水号
    @Override
    public void deleteTradeNo(String userId) {
        String tradeNoKey="user:"+userId+":tradeNo";
        redisTemplate.delete(tradeNoKey);
    }

    //验证商品的库存与价格
    @Override
    public String checkStoreAndPrice(String userId, OrderInfo orderInfo) {
        //a.拿到用户购买的商品清单
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        StringBuilder sb = new StringBuilder();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                Long skuId = orderDetail.getSkuId();
                String skuNum = orderDetail.getSkuNum();
                //b.判断库存是否足够，发起一个http请求
                String url="http://localhost:8100/hasStock?skuId="+skuId+"&num="+skuNum;
                String result = HttpClientUtil.doGet(url);
                //如果为0：无库存，1：有库存
                if ("0".equals(result)){
                    sb.append(orderDetail.getSkuName()+"库存不足,");
                }
                /**
                 *  判断价格
                 */
                BigDecimal realTimePrice = productFeignClient.getSkuPrice(skuId);
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                if (realTimePrice.compareTo(orderPrice)!=0){ //如果不相等
                    sb.append(orderDetail.getSkuName()+"sb价格有变化，需要刷新页面");
                }
            }
        }
        return sb.toString();
    }

    //根据订单id查询订单信息，也可以用一对多
    @Override
    public OrderInfo getOrder(Long orderId) {
        //1.订单的基本信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //2.订单的详情信息
        if (orderInfo!=null){
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
            orderInfo.setOrderDetailList(orderDetailList);
        }
        return orderInfo;
    }

    @Override
    public void updateOrderStatus(OrderInfo orderInfo,ProcessStatus processStatus) {
        orderInfo.setOrderStatus(processStatus.getOrderStatus().name());
        orderInfo.setProcessStatus(processStatus.name());
        baseMapper.updateById(orderInfo);
    }

    //通知库存系统减库存
    @Override
    public void sendMsgToWareHouse(OrderInfo orderInfo) {
        //a.将订单状态改为已通知仓库
        updateOrderStatus(orderInfo,ProcessStatus.NOTIFIED_WARE);
        //b.把数据组织为一个json数据给仓库系统
        Map<String,Object> dataMap=assembleWareHouseData(orderInfo);
        String dataMapJson= JSON.toJSONString(dataMap);
        //c.发送消息给仓库系统
        rabbitTemplate.convertAndSend(MqConst.DECREASE_STOCK_EXCHANGE,MqConst.DECREASE_STOCK_ROUTE_KEY,dataMapJson);
    }

    //拆单逻辑
    @Override
    public String splitOrder(Long orderId, String wareHouseIdSkuIdMapJson) {
        //1.获取原始订单
        OrderInfo parentOrderInfo = getOrder(orderId);
        //把接收到的信息转换为list[{"wareHouseId":"1","skuIdList":["24,26,28"]},{"wareHouseId":"2","skuIdList":["25,46"]}] 拆多少订单要看有多少仓库id\
        List<Map> wareHouseIdSkuIdMapList = JSON.parseArray(wareHouseIdSkuIdMapJson, Map.class);
        List<Object> assembleWareHouseDataList = new ArrayList<>();
        for (Map wareHouseIdSkuIdMap : wareHouseIdSkuIdMapList) {
            String wareHouseId = (String) wareHouseIdSkuIdMap.get("wareHouseId");
            List<String> skuIdList = (List<String>) wareHouseIdSkuIdMap.get("skuIdList");
            //2.设置子订单信息并保存
            OrderInfo childOrderInfo = new OrderInfo();
            BeanUtils.copyProperties(parentOrderInfo,childOrderInfo);
            childOrderInfo.setParentOrderId(orderId);
            childOrderInfo.setId(null);
            //设置仓库id
            childOrderInfo.setWareHouseId(wareHouseId);
            //3.设置子订单详情信息并保存
            List<OrderDetail> parentOrderDetailList = parentOrderInfo.getOrderDetailList();
            List<OrderDetail> childOrderDetailList = new ArrayList<>();
            //子订单总金额
            BigDecimal childTotalMoney=new BigDecimal(0);
            for (OrderDetail parentOrderDetail : parentOrderDetailList) {
                for (String skuId : skuIdList) {
                    if (parentOrderDetail.getSkuId()==Long.parseLong(skuId)){
                        BigDecimal orderPrice = parentOrderDetail.getOrderPrice();
                        String skuNum = parentOrderDetail.getSkuNum();
                        childTotalMoney=childTotalMoney.add(orderPrice.multiply(new BigDecimal(skuNum)));
                        childOrderDetailList.add(parentOrderDetail);
                    }
                }
            }
            childOrderInfo.setOrderDetailList(childOrderDetailList);
            childOrderInfo.setTotalMoney(childTotalMoney);
            //保存订单及订单详情
            saveOrderAndDetail(childOrderInfo);
            Map<String, Object> childOrderMap = assembleWareHouseData(childOrderInfo);
            assembleWareHouseDataList.add(childOrderMap);
        }
        //4.把原始订单状态改为split
        updateOrderStatus(parentOrderInfo,ProcessStatus.SPLIT);
        //5.返回信息给库存系统
        return JSON.toJSONString(assembleWareHouseDataList);
    }

    private Map<String, Object> assembleWareHouseData(OrderInfo orderInfo) {
        //构造一个map结构用于封装数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("orderId",orderInfo.getId());
        dataMap.put("consignee",orderInfo.getConsignee());
        dataMap.put("consigneeTel",orderInfo.getConsigneeTel());
        dataMap.put("orderComment",orderInfo.getOrderComment());
        dataMap.put("orderBody",orderInfo.getTradeBody());
        dataMap.put("deliveryAddress",orderInfo.getDeliveryAddress());
        dataMap.put("paymentWay",2);
        //需要设置一个仓库id 拆单的时候必须写
        if (!StringUtils.isEmpty(orderInfo.getWareHouseId())){
            dataMap.put("wareId",orderInfo.getWareHouseId());
        }

        //商品清单
        List<Object> orderDetailMapList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            Map<Object, Object> orderDetailMap = new HashMap<>();
            orderDetailMap.put("skuId",orderDetail.getSkuId());
            orderDetailMap.put("skuNum",orderDetail.getSkuNum());
            orderDetailMap.put("skuName",orderDetail.getSkuName());
            orderDetailMapList.add(orderDetailMap);
        }
        dataMap.put("details",orderDetailMapList);
        return dataMap;
    }
}
